<template>
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑公告' : '发布公告'"
      width="700px"
      :before-close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="localFormData"
        :rules="formRules"
        label-width="100px"
        label-position="right"
        class="notice-form"
      >
        <!-- 公告标题 -->
        <div class="form-row">
          <el-form-item label="公告标题" prop="title">
            <el-input
              v-model="localFormData.title"
              placeholder="请输入公告标题"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>
        </div>
  
        <!-- 公告类型和状态 -->
        <div class="form-row">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="公告类型" prop="type">
                <el-select
                  v-model="localFormData.type"
                  placeholder="请选择公告类型"
                  style="width: 100%"
                >
                  <el-option label="通知" :value="1" />
                  <el-option label="公告" :value="2" />
                  <el-option label="提醒" :value="3" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-select
                  v-model="localFormData.status"
                  placeholder="请选择状态"
                  style="width: 100%"
                >
                  <el-option label="草稿" :value="2" />
                  <el-option label="立即发布" :value="1" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
  
        <!-- 生效时间和失效时间 -->
        <div class="form-row">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="生效时间" prop="startTime">
                <el-date-picker
                  v-model="localFormData.startTime"
                  type="datetime"
                  placeholder="选择生效时间"
                  style="width: 100%"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="失效时间" prop="endTime">
                <el-date-picker
                  v-model="localFormData.endTime"
                  type="datetime"
                  placeholder="选择失效时间"
                  style="width: 100%"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
  
        <!-- 公告内容 -->
        <div class="form-row">
          <el-form-item label="公告内容" prop="content">
            <el-input
              v-model="localFormData.content"
              type="textarea"
              :rows="6"
              placeholder="请输入公告内容"
              maxlength="2000"
              show-word-limit
              resize="none"
            />
          </el-form-item>
        </div>
      </el-form>
  
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose" :disabled="loading">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleSubmit" 
            :loading="loading"
          >
            {{ loading ? '提交中...' : '确定' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </template>
  
  <script setup>
  import { ref, watch, nextTick } from 'vue'
  import { ElMessage } from 'element-plus'
  import { noticeApi } from '@/api/notice'
  
  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false
    },
    formData: {
      type: Object,
      default: () => ({})
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  })
  
  const emit = defineEmits(['update:modelValue', 'success'])
  
  // 响应式数据
  const dialogVisible = ref(false)
  const loading = ref(false)
  const formRef = ref()
  
  // 默认表单数据
  const defaultFormData = {
    title: '',
    content: '',
    type: 1,
    status: 2, // 默认草稿
    publisherName: '当前用户',
    startTime: '',
    endTime: ''
  }
  
  // 本地表单数据
  const localFormData = ref({ ...defaultFormData })
  
  // 表单验证规则
  const formRules = {
    title: [
      { required: true, message: '请输入公告标题', trigger: 'blur' },
      { min: 2, max: 100, message: '公告标题长度在 2 到 100 个字符', trigger: 'blur' }
    ],
    type: [
      { required: true, message: '请选择公告类型', trigger: 'change' }
    ],
    status: [
      { required: true, message: '请选择状态', trigger: 'change' }
    ],
    startTime: [
      { required: true, message: '请选择生效时间', trigger: 'change' }
    ],
    endTime: [
      { required: true, message: '请选择失效时间', trigger: 'change' },
      {
        validator: (rule, value, callback) => {
          if (!value) {
            callback()
            return
          }
          if (localFormData.value.startTime && value < localFormData.value.startTime) {
            callback(new Error('失效时间不能早于生效时间'))
          } else {
            callback()
          }
        },
        trigger: 'change'
      }
    ],
    content: [
      { required: true, message: '请输入公告内容', trigger: 'blur' },
      { min: 10, max: 2000, message: '公告内容长度在 10 到 2000 个字符', trigger: 'blur' }
    ]
  }
  
  // 监听props变化
  watch(() => props.modelValue, (val) => {
    dialogVisible.value = val
    if (val) {
      nextTick(() => {
        resetForm()
        initializeFormData()
      })
    }
  })
  
  // 监听dialogVisible变化
  watch(dialogVisible, (val) => {
    emit('update:modelValue', val)
  })
  
  // 初始化表单数据
  const initializeFormData = () => {
    if (props.isEdit && props.formData) {
      // 编辑模式：使用传入的数据
      const formData = {
        ...defaultFormData,
        ...props.formData
      }
      localFormData.value = { ...formData }
    } else {
      // 新增模式：重置为默认值
      localFormData.value = { ...defaultFormData }
      // 设置默认时间
      const now = new Date()
      const tomorrow = new Date(now.getTime() + 24 * 60 * 60 * 1000)
      localFormData.value.startTime = now.toLocaleString('zh-CN').replace(/\//g, '-').replace(/上午|下午/g, '').trim()
      localFormData.value.endTime = tomorrow.toLocaleString('zh-CN').replace(/\//g, '-').replace(/上午|下午/g, '').trim()
    }
  }
  
  // 重置表单验证
  const resetForm = () => {
    if (formRef.value) {
      formRef.value.clearValidate()
    }
  }
  
  // 关闭对话框
  const handleClose = () => {
    if (loading.value) {
      ElMessage.warning('正在提交，请稍候...')
      return
    }
    
    dialogVisible.value = false
    // 延迟重置表单，避免动画卡顿
    setTimeout(() => {
      localFormData.value = { ...defaultFormData }
    }, 300)
  }
  
  // 提交表单
  const handleSubmit = async () => {
    if (!formRef.value) {
      ElMessage.error('表单引用不存在')
      return
    }
  
    try {
      // 表单验证
      const valid = await formRef.value.validate()
      if (!valid) {
        return
      }
  
      loading.value = true
  
      // 准备提交数据
      const submitData = { ...localFormData.value }
  
      let response
      if (props.isEdit) {
        response = await noticeApi.updateNotice(submitData)
      } else {
        response = await noticeApi.addNotice(submitData)
      }
  
      // 判断响应结果
      if (response.code === 1) {
        ElMessage.success(props.isEdit ? '更新公告成功' : '发布公告成功')
        emit('success')
        handleClose()
      } else {
        ElMessage.error(response.msg || '操作失败')
      }
    } catch (error) {
      if (error.errors) {
        // 表单验证错误，Element Plus 会自动显示错误信息
        return
      }
      
      // 网络错误或其他异常
      if (error.response) {
        ElMessage.error(`服务器错误: ${error.response.data?.msg || error.response.status}`)
      } else if (error.request) {
        ElMessage.error('网络错误，请检查网络连接')
      } else {
        ElMessage.error('操作失败: ' + error.message)
      }
    } finally {
      loading.value = false
    }
  }
  
  // 暴露方法给父组件
  defineExpose({
    resetForm,
    handleClose
  })
  </script>
  
  <style scoped>
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    gap: 10px;
  }
  
  /* 表单间距调整 */
  :deep(.notice-form) {
    padding: 10px 0;
  }
  
  .form-row {
    margin-bottom: 24px;
  }
  
  .form-row:last-child {
    margin-bottom: 0;
  }
  
  :deep(.notice-form .el-form-item) {
    margin-bottom: 0;
  }
  
  :deep(.notice-form .el-form-item__label) {
    font-weight: 500;
    padding-right: 10px;
    color: #606266;
  }
  
  :deep(.notice-form .el-input) {
    width: 100%;
  }
  
  :deep(.notice-form .el-textarea) {
    width: 100%;
  }
  
  :deep(.notice-form .el-select) {
    width: 100%;
  }
  
  :deep(.notice-form .el-date-editor) {
    width: 100%;
  }
  
  :deep(.el-dialog__body) {
    padding: 20px 25px;
  }
  </style>